package com.lss.study.tool;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.cell.CellUtil;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.SheetUtil;
import org.apache.tomcat.util.http.fileupload.FileUtils;

import javax.swing.plaf.metal.MetalIconFactory;
import java.io.*;
import java.util.List;

/**
 * 功能描述：导入导出excel
 *
 * @Date: 2020/8/13 0:04
 */
public class ExcelHelper {
    public static void main(String[] args) throws IOException {
//        String path1 = "E:\\tmp\\aaa.xlsx";
//        String path2 = "E:\\tmp\\aaa";
//        exportSheet2Txt(path1, path2);
    }

    private static void exportSheet2Txt(String excelPath, String exportPath) throws IOException {
        StringBuilder str = new StringBuilder();
        File file = new File(excelPath);
        ExcelReader reader = ExcelUtil.getReader(file, 0);
        List<List<Object>> excelData = reader.read();
        reader.getSheetNames();
        writeTxt(excelData, exportPath);
    }

    private static void writeTxt(List<List<Object>> data, String path) {
        final String DELIMITER = "\t";
        File file = new File(path);
        try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) {
            for (List<Object> objects : data) {
                String rowData = List2Str(objects);
                bw.write(rowData);  // 将数据写入文件中
                bw.newLine();        // 新建一个换行符
                bw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String List2Str(List<Object> objects) {
        StringBuilder str = new StringBuilder();
        for (Object object : objects) {
            if (object == null) {
                str.append(" ");
            } else {
                str.append(object.toString());
            }
            str.append(" ");
        }
        return str.toString();
    }
}
